<?php

/*
 * This file is part of ibrand/EC-Open-Server.
 *
 * (c) iBrand <https://www.ibrand.cc>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace iBrand\EC\Open\Server\Http\Controllers;

use iBrand\Component\User\Repository\UserBindRepository;
use iBrand\Component\User\Repository\UserRepository;
use iBrand\Component\User\UserService;
use EasyWeChat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class MiniProgramLoginController extends Controller
{
    protected $userRepository;
    protected $userBindRepository;
    protected $userService;

    public function __construct(UserRepository $userRepository, UserBindRepository $userBindRepository
        , UserService $userService)
    {
        $this->userRepository = $userRepository;
        $this->userBindRepository = $userBindRepository;
        $this->userService = $userService;
    }


    public function wechattest(){

        $officialAccount = EasyWeChat::officialAccount();
        $token = $officialAccount->access_token->getToken();
        var_dump($token['access_token']);
        Redis::setex('lm_access_token_bengong_open',7000,$token['access_token']);

       /* $officialAccount = EasyWeChat::officialAccount();
        $card = $officialAccount->card;
        $code  = '751369311413';
        $cardId = 'p2k0WuFqAtmaYGsdyE8-8C1rS9Es';
        //拉取会员信息
        $result = $card->member_card->getUser($cardId, $code);
        //更新会员信息
        //$card->member_card->updateUser($info);
        var_dump($result);*/
    }

    public function login()
    {
        $code = request('code');
        if (empty($code)) {
            return $this->failed('缺失code');
        }

        $miniProgram = EasyWeChat::miniProgram();

        $result = $miniProgram->auth->session($code);

        if (!isset($result['openid'])) {
            return $this->failed('获取openid失败.');
        }

        $openid = $result['openid'];

        //1. openid 不存在相关用户和记录，直接返回 openid
        if (!$userBind = $this->userBindRepository->getByOpenId($openid)) {
            $userBind = $this->userBindRepository->create(['open_id' => $openid, 'type' => 'miniprogram',
                'app_id' => config('wechat.mini_program.default.app_id'),]);

            return $this->success(['open_id' => $openid]);
        }

        //2. openid 不存在相关用户，直接返回 openid
        if (!$userBind->user_id) {
            return $this->success(['open_id' => $openid]);
        }

        //3. 绑定了用户,直接返回 token
        $user = $this->userRepository->find($userBind->user_id);

        $token = $user->createToken($user->id)->accessToken;

        return $this->success(['token_type' => 'Bearer', 'access_token' => $token]);
    }

    public function mobileLogin(Request $request)
    {
        $miniProgram = EasyWeChat::miniProgram();

        //1. get session key.
        $code = $request->json('code');
        $result = $miniProgram->auth->session($code);

        if (!isset($result['session_key'])) {
            return $this->failed('获取 session_key 失败.');
        }

        $sessionKey = $result['session_key'];

        //2. get phone number.
        $encryptedData = $request->json('cryptData');
        $iv = $request->json('iv');
        $decryptedData = $miniProgram->encryptor->decryptData($sessionKey, $iv, $encryptedData);

        //3. get or create user.
        $unionid = isset($decryptedData['unionId'])?$decryptedData['unionId']:'';
        if (!$user = $this->userRepository->getUserByCredentials(['openid' => $decryptedData['openId']])) {
            $user = $this->userRepository->create([
                'openid' => $decryptedData['openId'],
                'unionid' => $unionid,
                'sex' => $decryptedData['gender'],
                'avatar' => $decryptedData['avatarUrl'],
                'nick_name' => $decryptedData['nickName'],
                'city' => $decryptedData['city'],
                'country' => $decryptedData['country'],
                'province' => $decryptedData['province'],
            ]);
        }
        $token = $user->createToken($user->id)->accessToken;
        $is_register = $user->mobile?1:0;

        //判断用户身份
        $ress = DB::table('good_girl')->where(['openid'=>$decryptedData['openId'],'status'=>1])->first();
        $is_vip = $ress?1:0;
        return $this->success(['token'=>$token,"info"=>$user->toArray(),'is_register'=>$is_register,'is_vip'=>$is_vip]);
    }
}
